<template>
  <el-dialog v-model="visible" title="导出中心" width="950" draggable :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <div class="flex py-4">
      <div class="left flex-1 mr-5">
        <div class="font-medium text-black">字段列表</div>
        <div style="width: 432px;">
          <el-table :data="export_field" height="600" style="width: 100%;" highlight-current-row :header-cell-style="{
            background: '#F6FAFF'
          }" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="field_name" label="字段" />
            <el-table-column prop="opearn" label="排序" width="120">
              <template #default="scope">
                <el-link type="primary" :underline="false" @click="moveUp(scope.$index, scope.row)">上移</el-link>
                <el-divider direction="vertical" />
                <el-link type="primary" :underline="false" @click="moveDown(scope.$index, scope.row)">下移</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="right flex-1">
        <div class="font-medium text-black">字段列表</div>
        <div class="flex justify-between items-end mb-4">
          <el-button type="primary" @click="handleImport">导出</el-button>
          <!-- <el-button type="primary">按订单维度导出</el-button> -->
          <div class="flex text-xs text-gray-400 ml-5"> <svg-icon icon-class="hint_line01"></svg-icon>导出结果在 <el-link
              type="primary" :underline="false" @click="navPersonal">个人中心</el-link> 查看</div>
        </div>
        <div class="flex items-center mb-2">
          <el-input v-model="exportName" class="w-full" placeholder="请输入名称" /><el-button type="primary" plain
            @click="saveTemplate">保存模版</el-button>
        </div>
        <el-table :data="templates" style="width: 100%" highlight-current-row :header-cell-style="{
          background: '#F6FAFF'
        }" border>
          <el-table-column prop="name" label="名称" width="300" />
          <el-table-column prop="opearn" label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="exportRow(scope.row)">导出</el-button>
              <template v-if="scope.row.creator_id == user_id">
                <el-divider direction="vertical" />
                <el-button type="danger" link @click="exportDelete(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="DerivedCenter">

import { reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import { getExportConfig, exportRord, exporttpl, exportTemplateOne, exportTemplateDelete } from '@/api/public'
import { ElMessage } from 'element-plus'
import action from '@/utils/action.js'

const { proxy } = getCurrentInstance()
const emits = defineEmits(['query'])
const props = defineProps({
  options: {
    type: Object,
    required: true
  }
})

const data = reactive({
  form: {
    title: '',
    module: 'goods',
    config_id: null,
    condition: null,
  },
  visible: false,
  loading: false,
  export_field: [],
  multipleSelection: [],
  exportName: '',
  templates: [],
  user_id: '',
  tag_name: ''
})
const { visible, export_field, multipleSelection, form, exportName, templates, user_id,tag_name } = toRefs(data)
const open = (item) => {
  visible.value = true
  form.value.config_id = item.id
  form.value.condition = item.condition
  tag_name.value = item.tag_name
  getDetail(item.id)
  getTemplate()
}
const getDetail = async (id) => {
  try {
    const res = await getExportConfig(id)
    export_field.value = res.data.export_field
    form.value.title = res.data.conf_name + window.userInfo.user.realname
  } catch (e) {
    throw Error(e)
  }
}

const getTemplate = async () => {
  try {
    const res = await exportTemplateOne({
      home_system: 4,
      tag_name: tag_name.value
    })
    templates.value = res.data.templates
  } catch (e) {
    throw Error(e)
  }
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const moveUp = (index, row) => {
  if (index > 0) {
    const upDate = export_field.value[index - 1];
    export_field.value.splice(index - 1, 1);
    export_field.value.splice(index, 0, upDate);
  } else {
    ElMessage.error("已经是第一条，不可上移");
  }
}
// 下移
const moveDown = (index, row) => {
  if (index + 1 === export_field.value.length) {
    ElMessage.error("已经是最后一条，不可下移");
  } else {
    const downDate = export_field.value[index + 1];
    export_field.value.splice(index + 1, 1);
    export_field.value.splice(index, 0, downDate);
  }
}

const handleImport = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('至少勾选一条导出项')
    return
  }

  const fields = multipleSelection.value.map(i => i.field_key)
  try {
    const res = await exportRord({
      ...form.value,
      fields
    })
    ElMessage.success(res.message)
  } catch (e) {
    throw Error(e)
  }
}


const navPersonal = async () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      path: "/user/profile",
      type: "push"
    }
  })
}

const saveTemplate = async () => {
  if (!exportName.value) {
    ElMessage.error('请输入名称')
    return
  }
  if (multipleSelection.value.length == 0) {
    ElMessage.error('至少勾选一条导出项')
    return
  }

  const fields = multipleSelection.value.map(i => i.field_key)

  try {
    const res = await exporttpl({
      config_id: form.value.config_id,
      name: exportName.value,
      fields
    })
    ElMessage.success(res.data.message)
    getTemplate()
  } catch (e) {
    throw Error(e)
  }
}

const exportRow = async (row) => {
  const title = row.name + window.userInfo.user.realname
  try {
    const res = await exportRord({
      tpl_id: row.tpl_id,
      title,
      ...form.value,
      fields: []
    })
    ElMessage.success(res.message)
  } catch (e) {
    throw Error(e)
  }
}

const exportDelete = async (row) => {
  try {
    const res = await exportTemplateDelete(row.tpl_id)
    ElMessage.success(res.data.message)
    getTemplate()
  } catch (e) {
    throw Error(e)
  }
}

onMounted(() => {
  user_id.value = window.userInfo?.user?.user_id
})

const close = () => {
  exportName.value = ''
  visible.value = false
}
defineExpose({ open })
</script>
